<template>
  <edit-card :title="title" :type="type" :loading="globalLoading" @confirm="confirmTask">
    <div class="edit-task">
      <a-form
        ref="caseFormRef"
        :model="formState"
        :rules="caseRules"
        :label-col="{ style: { width: '120px' } }"
        class="w-560"
        label-align="left"
      >
        <a-form-item label="项目案例名称" name="projectName">
          <a-input v-model:value="formState.projectName" v-trim class="w-440" placeholder="请输入项目案例名称" :maxlength="200" />
        </a-form-item>

        <a-form-item label="类别" name="projectLabelIds">
          <a-select
            v-model:value="formState.projectLabelIds"
            class="w-440"
            :show-search="false"
            :options="statusOptions"
            :field-names="{ label: 'labelName', value: 'labelId' }"
            mode="multiple"
            max-tag-count="responsive"
            placeholder="请选择类别"
            style="width: 100%"
            show-arrow
            :disabled="!checkKey(['admin-case-manage-create', 'admin-case-manage-edit'])"
          />
        </a-form-item>

        <a-form-item label="在线体验" name="onlineExperience">
          <a-select
            v-model:value="formState.onlineExperience"
            class="w-440"
            allow-clear
            :show-search="false"
            :options="onlineOptions"
            placeholder="请选择在线体验"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="formState.description"
            v-trim
            class="w-440"
            placeholder="请输入描述"
            :rows="5"
            :maxlength="200"
            show-count
          />
        </a-form-item>

        <a-form-item label="项目介绍文档" name="introduceUrl">
          <file-upload
            v-model:file-url="formState.introduceUrl"
            class="file-upload w-440"
            :max-count="1"
            :is-preview="false"
            accept="pdf,ppt,pptx,doc,docx"
            suffix="doc"
            :module-prefix="'proj'"
          >
            <a-button
              type="dashed"
              size="small"
              class="icon-with-btn btn-mini"
              :disabled="!checkKey(['admin-case-manage-create', 'admin-case-manage-edit'])"
            >
              <i class="iconfont icon-upload-line"></i>
              上传
            </a-button>
          </file-upload>
        </a-form-item>

        <a-form-item label="数据集" name="dataUrl">
          <div>
            <file-upload
              v-model:file-url="formState.dataUrl"
              class="w-440 file-upload"
              :max-count="1"
              :is-preview="false"
              suffix="zip"
              accept="zip"
              :module-prefix="'proj'"
            >
              <a-button
                type="dashed"
                size="small"
                class="icon-with-btn btn-mini"
                :disabled="!checkKey(['admin-case-manage-create', 'admin-case-manage-edit'])"
              >
                <i class="iconfont icon-upload-line"></i>
                上传
              </a-button>
            </file-upload>
          </div>
        </a-form-item>

        <a-form-item label="源代码" name="sourceUrl">
          <file-upload
            v-model:file-url="formState.sourceUrl"
            class="w-440 file-upload"
            :max-count="1"
            :is-preview="false"
            suffix="zip"
            accept="zip"
            :module-prefix="'proj'"
          >
            <a-button
              type="dashed"
              size="small"
              class="icon-with-btn btn-mini"
              :disabled="!checkKey(['admin-case-manage-create', 'admin-case-manage-edit'])"
            >
              <i class="iconfont icon-upload-line"></i>
              上传
            </a-button>
          </file-upload>
        </a-form-item>
      </a-form>
    </div>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { computed, onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import FileUpload from '@/components/upload/FileUpload/index.vue'
  import { checkKey } from '@/directives/auth'
  import { adminCaseManageApi, tagManageApi } from '@/services/api'
  import { countStrToBit, validateDirName } from '@/utils'

  import { CaseDetailsType, DictionaryType, Form, OnlineStatus, ProjectLabelInfoVO, TaskStatus } from '../types'

  const route = useRoute()

  const router = useRouter()
  const caseFormRef = ref()

  const caseId = route.params.id as string | ''

  const formState = ref<Form>({
    projectName: '',
    description: '',
    projectLabelIds: [],
    onlineExperience: '',
    introduceUrl: '',
    dataUrl: '',
    sourceUrl: ''
  })
  const detailData = ref<CaseDetailsType>({})

  let statusOptions = ref<TaskStatus[]>([])
  let onlineOptions = ref<OnlineStatus[]>([
    {
      label: '基于人体关键点检测的上半身衣服颜色分析',
      value: 'clothingColorAnalysis'
    },
    {
      label: '基于人体检测的区域内人数统计',
      value: 'populationStatistics'
    }
  ])

  const type = ref((caseId ? 'edit' : 'add') as 'edit' | 'add')

  const title = computed(() => {
    return caseId ? `编辑案例（${detailData.value.projectName || ''}）` : '新建案例'
  })
  const validateByte = async (rule: Rule, value: string) => {
    const byteCount = countStrToBit(value)
    if (byteCount === 0) {
      return Promise.reject('请输入项目案例名称')
    } else if (byteCount > 200) {
      return Promise.reject('名称不可超过200字节')
    }
    return Promise.resolve()
  }

  const caseRules: Record<string, Rule[]> = {
    // projectName: [{ required: true, trigger: 'change', message: '请输入项目案例名称' }],
    projectName: [{ validator: validateDirName() }, { required: true, trigger: 'change', validator: validateByte }],

    projectLabelIds: [
      {
        required: true,
        message: '请选择类别'
      }
    ],
    introduceUrl: [{ required: true, message: '请上传项目介绍文档', trigger: 'change' }],
    dataUrl: [{ required: true, message: '请上传数据集', trigger: 'change' }],
    sourceUrl: [{ required: true, message: '请上传源代码', trigger: 'change' }]
  }
  //获取分类字典信息
  const { loading: getDictionLoading, runAsync: getDictionaryRun } = useRequest<ResponseData<DictionaryType[]>>(tagManageApi.list, {
    onSuccess: ({ data }) => {
      statusOptions.value = [
        ...statusOptions.value,
        ...data.map((item: DictionaryType) => ({ labelName: item.v, labelId: item.id }))
      ] as TaskStatus[]
    }
  })
  //全局Loading
  const globalLoading = computed(() => {
    return getDictionLoading.value || getDetailLoading.value || addLoading.value || updateLoading.value
  })

  // TODO:确定
  const confirmTask = () => {
    caseFormRef.value
      .validate()
      .then(() => {
        submitForm()
      })
      .catch((err: any) => {
        console.log(err)
      })
  }
  //新增
  const { loading: addLoading, runAsync: runAddAsync } = useRequest(adminCaseManageApi.add)
  //修改
  const { loading: updateLoading, runAsync: runUpdateAsync } = useRequest(adminCaseManageApi.update)

  //点击确定
  const submitForm = async () => {
    formState.value.onlineExperience = formState.value.onlineExperience || ''
    const params = { ...formState.value }
    const isAdd = type.value === 'add'
    console.log(params, 'params')

    try {
      await (isAdd ? runAddAsync(params, { isAddUid: true }) : runUpdateAsync({ ...params, id: caseId }, { isAddUid: true }))
      message.success('操作成功')
      goBack()
    } catch (error) {
      console.log(error)
    }
  }
  const goBack = () => {
    router.go(-1)
  }
  //获取详情数据
  const { loading: getDetailLoading, runAsync: runGetCaseDetail } = useRequest<ResponseData<CaseDetailsType>>(
    (id: string) => adminCaseManageApi.detail(id)(),
    {
      onSuccess: ({ data }) => {
        Object.assign(detailData.value, data)
        Object.assign(formState.value, data, {
          projectLabelIds: data.projectLabelInfoVOS ? data.projectLabelInfoVOS.map((item: ProjectLabelInfoVO) => item.labelId) : []
        })
        // delete formState.value.updateTime
        Reflect.deleteProperty(formState.value, 'updateTime')
        console.log(formState.value, 'formState')
      }
    }
  )
  const getDetailData = (id: string) => {
    runGetCaseDetail(id)
  }
  onMounted(async () => {
    type.value === 'edit' && getDetailData(caseId)
  })
  getDictionaryRun({
    type: 'proj'
  })
</script>
<style lang="less" scoped>
  .edit-task {
    :deep(.ant-form-item) {
      margin-bottom: 40px;
    }

    :deep(.ant-form-item-label > label::after) {
      display: none;
    }

    :deep(.ant-radio-wrapper) {
      margin-right: 24px;
    }

    .ant-radio-wrapper :deep(.ant-transfer-list) {
      position: relative;

      .ant-transfer-list-header {
        height: 39px;
        background: #fafafa;
      }

      &:first-child {
        .ant-transfer-list-header {
          &::after {
            content: '待选';
            position: absolute;
            right: 8px;
          }
        }
      }

      &:last-child {
        .ant-transfer-list-header {
          &::after {
            content: '已选';
            position: absolute;
            right: 8px;
          }
        }
      }

      .ant-input-affix-wrapper {
        height: 32px;
        min-height: 32px !important;
      }
    }

    .tag-select {
      display: flex;

      .left {
        margin-right: 80px;
      }
    }
  }
</style>
